import { createSlice } from "@reduxjs/toolkit";
import { setToken as _setToken,getToken, removeToken} from "@/utils";
import {loginAPI, getUserInfoAPI } from "@/apis/user";

const userStore=createSlice({
    name:'user',
    initialState:{
        token:getToken() || '',
        userInfo:{}
    },
    //同步修改方法
    reducers:{
        setToken(state,action){
            state.token=action.payload
            //本地存取
           _setToken(action.payload)
        },
        //修改用户信息
        setUserInfo(state,action){
            state.userInfo=action.payload
        },
        clearUserInfo(state){
            state.token=''
            removeToken()
            state.userInfo={}
        }
    }
})

//解构actionCreater
const {setToken,setUserInfo,clearUserInfo}=userStore.actions

//获取reducer函数

const userReducer=userStore.reducer

//异步方法
const fetchLogin=(loginForm)=>{
   return async(dispacth)=>{
     //1,发送异步请求
    const res=await loginAPI(loginForm)
      //2.提交异步请求
      dispacth(setToken(res.data.data.token))
   }
}

//获取用户信息
const fetchUserInfo=()=>{
    return async(dispacth)=>{
      //1,发送异步请求
     const res=await getUserInfoAPI()
       //2.提交异步请求
       dispacth(setUserInfo(res.data.data))
    }
 }

export {setToken,fetchLogin,fetchUserInfo,clearUserInfo}
export default userReducer